package dao;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.ext.Db4oException;
import javax.swing.JOptionPane;

public class DAO {
  
  private static ObjectContainer db = null;


  public static ObjectContainer getObjectContainer() {
    if (DAO.db == null) {
      try {
        DAO.db = Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(),"xarifado.db");
      } catch (Db4oException e) {
        JOptionPane.showMessageDialog(null, "Não pode haver mais de um aplicativo aberto!!!",
                null, JOptionPane.WARNING_MESSAGE);
        System.exit(0);
        return null;
      }
    }
      
    return DAO.db;
  }
  
  public static void closeObjectContainer() {
    if (DAO.db != null) {
      DAO.db.close();
      DAO.db = null;
    }
  }
    
  public static Object[] getListObjects(Object proto) {
    ObjectSet result = DAO.getObjectContainer().queryByExample(proto);
    return result.toArray();
  }
  
  //C(reate)R(etrieve)U(pdate)D(elete)
  public static boolean create(Object o) {
        DAO.getObjectContainer();
        try {
            DAO.db.store(o);
            DAO.db.commit();
            return true;
        } catch (Db4oException e) {
            return false;
        }
  }
      
  public static Object retrieve(Object proto) {
    ObjectSet result = DAO.getObjectContainer().queryByExample(proto);
    if (result.hasNext())
      return result.next();
    return null;
  }

  public static boolean delete(Object proto){
    DAO.getObjectContainer();
    try {
        DAO.db.delete(proto);
        DAO.db.commit();
        return true;
    } catch (Db4oException e) {
        return false;
    }     
  }
}